package cn.jinjimi.app.main.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.ShareProxy;
import cn.jinjimi.app.bean.WXPayResult;
import cn.jinjimi.app.main.dialog.ShareDialog;
import cn.jinjimi.app.webview.WebViewJavascriptBridge;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.controller.event.LoginSuccessEvent;
import cn.jinjimi.app.controller.event.LogoutEvent;
import cn.jinjimi.app.main.extend.WebViewFragment;
import cn.jinjimi.app.webview.bean.ShareAction;
import cn.jinjimi.base.util.URLUtil;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 *
 * @author zhenhua
 * @date 2018/1/27
 */

public class MainWebViewFragment extends WebViewFragment {

    private String mUrl;
    private WebViewJavascriptBridge handler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        loadUrl(getArguments());
    }

    @Override
    public void onResume() {
        super.onResume();
        loadUrl(getArguments());
    }

    private void loadUrl(Bundle data) {
        //load url.
        if (data != null) {
            mUrl = data.getString(Constants.BundleKey.URL);
            if (!TextUtils.isEmpty(mUrl)) {
                //getWebView().loadUrl("file:///android_asset/webviewJavascriptBridge.html");
                getWebView().loadUrl(appendParams(mUrl));
            }
        }
    }

    private String appendParams(String url) {
        String token = AccountManager.getInstance().getToken();
        return URLUtil.appendParam(url, Constants.ParamKey.APP_TOKEN, token);
    }

    protected void reload() {
        loadUrl(getArguments());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginSuccess(LoginSuccessEvent event) {
        reload();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLogout(LogoutEvent event) {
        reload();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(WXPayResult result) {

    }
}
